/******************************************************************************
*
* This file is part of FreeTrack (http://code.google.com/p/qtfreetrack).
* BY Willy Gardiol (willy@gardiol.org)
*
* FreeTrack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FreeTrack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar.  If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/

#include "workerclearcache.h"

#define MAKE_CHUNK_KEY(xa12,ya12,za12) za12*100000+ya12*1000+xa12

WorkerClearCache::WorkerClearCache(const QString& filename,
                                     const QString& cbn,
                                     const QHash<int,int>& cc,
                                     const QHash<int,int>& cr ) :
    WorkerProcess(2)
{
    chunks_rows = cr;
    chunks_cols = cc;
    image_filename = filename;

    // Build filenames:
    foreach( int z, chunks_rows.keys() )
        for ( int chunk_row = 0; chunk_row < chunks_rows.value(z,0); chunk_row++ )
            for ( int chunk_col = 0; chunk_col < chunks_cols.value(z,0); chunk_col++ )
                chunk_filenames.append( cbn.arg( chunk_col).arg( chunk_row ).arg( z ) );
}

WorkerClearCache::~WorkerClearCache()
{
}

bool WorkerClearCache::do_stuff()
{
    int tot_files = chunk_filenames.count();
    int cur = 0;
    QString path = "";
    QString msg = QString(tr("Deleting file")+" (%1/%2)");
    foreach ( QString filename, chunk_filenames )
    {
        if ( path == "" )
            path = QFileInfo( filename ).filePath();

        sendUpdate( msg.arg(cur).arg(tot_files), 0, 0, tot_files, cur );
        sendUpdate( tr("deleting..."), 1, 0, 1, 0 );
        if ( please_terminate )
            break;

        if ( QFile::exists( filename ) )
        {
            if ( !QFile::remove( filename ) )
            {
                setErrorString( tr("Unable to delete file: ") + filename );
                return false;
            }
        }
        sendUpdate( tr("deleted!"), 1, 0, 1, 1 );
        cur++;
    }
    if ( path != "" )
        QDir( QFileInfo(path).filePath() ).rmdir( QFileInfo(path).fileName() );
    return true;
}

